package cn.hicard.util;

import java.util.List;

import org.apache.log4j.Logger;

import cn.hicard.risk.common.Constant;
import cn.hicard.risk.service.bd.CardbinService;

/**
 * 交易卡的信息工具类
 * @author zhangyu
 *
 */
public class CardInfo {

	private static Logger logger = Logger.getLogger(Constant.LOGGER_MAIN);
	
	// 保存所有信用卡的发行数据issue_data
	private static List<String> cardIssues = null;
		
	// 查询所有卡BIN的issue_data数据集合
	private static void initCardIssues(){
		logger.debug("查询所有卡BIN的issue_data数据集合开始");
		CardbinService service = (CardbinService)SpringContext.getBean("cardbinService");
		
		try {
			cardIssues = service.getCardIssues();
		} catch (Exception e) {
			logger.error("查询所有卡BIN的issue_data异常", e);
		}
		
		logger.debug("查询所有卡BIN的issue_data数据集合结束");
		logger.info("查询并取得所有卡BIN的issue_data数据集合，数据长度：" + cardIssues.size());
	}
	
	/** 获取卡类型<br/> 
	 * 1 为信用卡; 2 为借记卡
	 * */
	public static String getCardtype(String cardno){
		if(isCreditCard(cardno)){
			return "1";
		}else{
			return "2";
		}
	}
	
	/** 获取卡类型名称<br/> 
	 * 1 为信用卡; 2 为借记卡
	 * */
	public static String getCardtypeName(String cardtype){
		if("1".equals(cardtype)){
			return "信用卡";
		}else if("2".equals(cardtype)){
			return "借记卡";
		}else{
			return "未知";
		}
	}
	
	/** 判断是否为信用卡 */
	public static boolean isCreditCard(String cardno){		
		
		if(cardIssues == null){
			initCardIssues();
		}		
		
		if(cardno == null){
			return false;
		}
		
		if(cardno.length()>= 6 && cardIssues.contains(cardno.substring(0,6))){
			return true;
		}
		if(cardno.length()>= 8 && cardIssues.contains(cardno.substring(0,8))){
			return true;
		}
		if(cardno.length()>= 7 && cardIssues.contains(cardno.substring(0,7))){
			return true;
		}
		if(cardno.length()>= 5 && cardIssues.contains(cardno.substring(0,5))){ 
			return true;
		}
		if(cardno.length()>= 4 && cardIssues.contains(cardno.substring(0,4))){
			return true;
		}
		if(cardno.length()>= 3 && cardIssues.contains(cardno.substring(0,3))){
			return true;
		}
		if(cardno.length()>= 2 && cardIssues.contains(cardno.substring(0,2))){
			return true;
		}
		
		return false;
	}
}
